<template>
  <div>
    <HETTable1
        ref="strategyBackupTable"
        :tableData="data.tableData"
        :tHead="data.tHead"
        :total="data.total"
        :headerOperation="data.headerOperation"
        @getTableData="initTable"
    >
      <template #status>
        <el-table-column label="状态">
          <template #default="scope">
            {{
              scope.row.status == 0 ? "备份中" : scope.row.status == 1 ? "成功" : "失败"
            }}
          </template>
        </el-table-column>
      </template>
      <template #createTime>
        <el-table-column label="创建时间">
          <template #default="scope">
            <div>{{ moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
          </template>
        </el-table-column>
      </template>
      <template #operation>
        <el-table-column label="操作">
          <template #default="scope">
            <span class="mr-6">
              <el-text class="cursor-pointer" type="primary" @click="dowload(scope.row.id)">下载</el-text>
            </span>
            <el-text class="cursor-pointer" type="primary" @click="del(scope.row.id)">删除</el-text>
          </template>
        </el-table-column>
      </template>
    </HETTable1>
    <el-dialog
        :model-value="dialogAsync"
        :center="true"
        width="30%"
        title="上传备份文件"
        :close-on-click-modal="false"
        @close="dialogAsync = false"
    >
      <el-form class="upload-backups">
        <el-form-item label="备份文件：">
          <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="#"
              :on-change="onSuccess"
              :on-exceed="handleExceed"
              :limit="1"
              :auto-upload="false"
              accept=".tar.gz"
          >
            <el-button type="primary">浏览</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, markRaw} from "vue";
import {
  req_getStartegyBackupList,
  req_getStartegyBackupCounts,
  req_backupStrategy,
  req_restoreBackupStrategy,
  req_delStrategyBackup,
} from "~/utils/axios/index.js";
import {Upload, DocumentCopy} from "@element-plus/icons-vue";
import moment from "moment";
import {ElMessage, ElMessageBox, genFileId} from "element-plus";
import {useTreeStore} from "~/utils/pinia/tree.js";
import {URI} from "~/utils/axios/axios.js";
import {useUserStore} from "~/utils/pinia/user.js"

const dialogAsync = ref(false);
const strategyBackupTable = ref();
const uploadRef = ref();
const userStore = useUserStore();
// treeStore.treeLinkedTableRef = strategyBackupTable;

const backup = () => {
  req_backupStrategy().then((res) => {
    res.data.succeed ? ElMessage.success(res.data.data) : ElMessage.error("备份失败");
    strategyBackupTable.value.getTableData();
  });
};

const del = (id) => {
  ElMessageBox.confirm("确定要删除选中的策略备份？", "删除策略备份", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    center: true,
    closeOnClickModal: false,
  }).then(() => {
    req_delStrategyBackup(id).then((res) => {
      res.data.succeed ? ElMessage.success("删除成功") : ElMessage.error("删除失败");
      strategyBackupTable.value.getTableData();
    });
  });
};
const dowload = (id) => {
  let link = document.createElement("a");
  link.href =
      window.location.protocol +
      "//" +
      window.location.host +
      URI +
      "globalStrategy/backup/download?id=" +
      id;
  link.click();
};

const data = reactive({
  tHead: [
    {
      label: "文件名",
      prop: "fileName",
      isCustom: false,
    },
    {
      label: "状态",
      prop: "status",
      isCustom: true,
      slotName: "status",
    },
    {
      label: "创建时间",
      prop: "createTime",
      isCustom: true,
      slotName: "createTime",
    },
    {
      label: "操作",
      prop: "operation",
      isCustom: true,
      slotName: "operation",
    },
  ],
  tableData: [],
  total: null,
  headerOperation: [
    {
      name: "备份",
      icon: markRaw(DocumentCopy),
      handleClick: backup,
    },
    {
      name: "恢复",
      icon: markRaw(Upload),
      handleClick: () => {
        dialogAsync.value = true;
      },
    },
  ],
});
const handleExceed = (files) => {
  uploadRef.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};
const onSuccess = (file) => {
  if (file.status === "ready") {
    // 创建 FormData 对象
    let formData = new FormData();
    // 添加文件到 FormData 对象
    // formData.append("id", "WU_FILE_0");
    formData.append("file", file.raw);
    // formData.append("name", file.name);
    // formData.append("type", "application/octet-stream");
    // formData.append("lastModifiedDate", new Date());
    // formData.append("size", file.size);
    req_restoreBackupStrategy(formData).then((res) => {
      res.data.succeed ? ElMessage.success(res.data.data) : ElMessage.error("上传失败");
      dialogAsync.value = false;
      uploadRef.value.clearFiles();
    });
  }
};
const initTable = async (initTableParams) => {
  strategyBackupTable.value.loading();
  let params = {
    $skip: initTableParams.page * initTableParams.size,
    $limit: initTableParams.size,
  };
  try {
    const {data: res} = await req_getStartegyBackupList(params);
    const {data: count} = await req_getStartegyBackupCounts();
    strategyBackupTable.value.finish();
    data.tableData = res || [];
    data.total = count || 0;
  } catch (err) {
    strategyBackupTable.value.finish();
  }
  if (userStore) {
    userStore.socket.addListener("backup", backupEvent);
  }
};

const backupEvent = (message) => {
  console.log(message);
  if (strategyBackupTable) {
    strategyBackupTable.value.getTableData();
    ElMessage({
      message: message.message,
      type: 'success',
    })
  }
}
</script>

<style lang="scss" scoped>
:deep(.upload-backups .asterisk-left){
  margin-bottom: 0 !important;
}
</style>
